package entity

import (
	"encoding/json"
	"github.com/golang/protobuf/proto"
	"kop/modules/treasure/consts"
	"kop/pb"
	"kop/pb/service"
	"time"
)

// 航海宝藏
type Treasure struct {
	RoleID      int32 `gorm:"type:int;primary_key"`
	MapID       int32
	PlayNum     int32
	Cells       []byte
	Number      int32 // 探索次数
	Point1      int32
	Point2      int32
	Point3      int32
	Point4      int32
	Buff1       int32
	Buff2       int32
	Buff3       int32
	BuffOptions []byte `gorm:"type:jsonb"` //
	CreatedAt   time.Time
	UpdatedAt   time.Time

	CellsArr       []*pb.Cell `sql:"-"`
	BuffOptionsArr []int32    `sql:"-"`
}

func (t *Treasure) AfterFind() error {

	var cells service.Cells
	var err = proto.Unmarshal(t.Cells, &cells)

	if err != nil {
		return err
	}

	t.CellsArr = cells.Cells

	if t.MapID == 0 {
		// 完成夺宝后才开始计时
		if t.PlayNum < consts.MaxPlayNum {
			// 每4小时恢复1点免费游玩次数
			var n = int32(time.Now().Sub(t.UpdatedAt).Seconds() / consts.Interval)
			t.PlayNum += n
			if t.PlayNum > consts.MaxPlayNum {
				t.PlayNum = consts.MaxPlayNum
			}
		}
	}

	var buffOptions []int32
	_ = json.Unmarshal(t.BuffOptions, &buffOptions)
	t.BuffOptionsArr = buffOptions

	return nil
}

func (t *Treasure) BeforeSave() error {

	var err error
	t.Cells, err = proto.Marshal(&(service.Cells{Cells: t.CellsArr}))
	t.BuffOptions, _ = json.Marshal(t.BuffOptionsArr)

	return err
}

func (t *Treasure) BeforeUpdate() error {

	var err error
	t.Cells, err = proto.Marshal(&(service.Cells{Cells: t.CellsArr}))
	t.BuffOptions, _ = json.Marshal(t.BuffOptionsArr)

	return err
}
